package org.personal.servlet;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.myhibernate.ProxyTemplate;
import org.myhibernate.Template;
import org.myhibernate.core.method.PageSizeQuery;
import org.personal.Constants;
import org.personal.entity.Portlet;
import org.personal.entity.User;
import org.personal.util.UserUtil;

import com.util.ConfigUtil;

public class PortletServlet extends HttpServlet
{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException 
	{
		String portletId=request.getParameter("portletId")+"";
		//System.out.println("PortletServlet portletId="+portletId);
		response.setCharacterEncoding("utf-8");
		User user=(User) request.getSession().getAttribute(Constants.USER);
		String tipMessage="";
		Portlet portlet=null;
		Template<Portlet> template=new ProxyTemplate(Portlet.class).getInstance();
		try 
		{
			portlet=template.get(Integer.parseInt(portletId));
			UserUtil userUtil=new UserUtil();
			if (portlet !=null)
			{
				PageSizeQuery<Portlet> query=template.getPageSizeQuery();
				if (user !=null)
				{
					//有用户
					List<String> groups=userUtil.copyList(user.getGroups());
					groups.add(Constants.USER_ALLUSER);
					groups.add(user.getUid());
					if (userUtil.hasCommon(portlet.getUsers(), groups)==false)
					{
						portlet=null;
						tipMessage=ConfigUtil.getAttribute("portlet.tip.message.noright")+" "+portlet.getTitle();
					}
				} else
				{
					//匿名用户是否有权限
					List<String> users=new LinkedList<String>();
					users.add(Constants.USER_ANONYMOUS);
					if (userUtil.hasCommon(portlet.getUsers(), users)==false)
					{
						portlet=null;
						tipMessage=ConfigUtil.getAttribute("portlet.tip.message.noright")+" "+portlet.getTitle();
					}
				}
			}//endif portlet!=null
			else {
				tipMessage=ConfigUtil.getAttribute("portlet.tip.message.noexist");
			}
		} catch (Exception e) 
		{
			e.printStackTrace();
			response.getWriter().print("<span>"+e.toString().trim()+"</span>");
		}
		finally
		{
			template.close();
		}
		if (portlet!=null)
		{
			//System.out.println("PortletServlet pagePath="+portlet.getPagePath());
			request.setAttribute(Constants.PORTLET,portlet);
			request.getRequestDispatcher(portlet.getPagePath()).forward(request,response);
		}else
		{
			if (Constants.PORTLET_TIP)
			{
				response.getWriter().print("<font color=\"red\" style=\"color:red;\" >"+tipMessage+"</font>");
			}else {
				response.getWriter().print("");
			}
		}
		
	}
}
